<?php

namespace app\data\controller\api\auth;

use app\data\controller\api\Auth;
use app\data\service\UserAdminService;

/**
 * 商品评价数据接口
 * Class Goods
 * @package app\data\controller\api
 */
class Comment extends Auth
{
    /**
     * 提交评论
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DbException
     */
    public function postComment()
    {
        $data = $this->_vali([
            'uuid.value'            => $this->uuid,
            'items.require' => '商品数据不能为空',
            'order_no.require'      => '单号不能为空',
        ]);

        $userInfo = UserAdminService::instance()->get($data['uuid']);

        // 订单商品处理
        foreach ($data['items'] as &$item) {

            if (!isset($item['goods_name'])) {
                $this->error('商品名称不能为空');
            }
            if (!isset($item['goods_code'])) {
                $this->error('商品编码不能为空');
            }
            if (!isset($item['goods_sku'])) {
                $this->error('商品规格不能为空');
            }
            if (!isset($item['goods_spec'])) {
                $this->error('商品规格不能为空');
            }
            if (!isset($item['order_item_id'])) {
                $this->error('子订单编号不能为空');
            }
            if (!isset($item['star'])) {
                $this->error('星级评分不能为空');
            }
            if (!isset($item['comment'])) {
                $this->error('评价不能为空');
            }

            foreach ($item as $key => $value) {
                if (!in_array($key, ['goods_name', 'goods_code', 'goods_sku', 'goods_spec', 'order_item_id', 'star', 'comment', 'media'])) {
                    unset($item[$key]);
                }
            }

            $item['uuid'] = $data['uuid'];
            $item['order_no'] = $data['order_no'];
            $item['phone'] = $userInfo['phone'];
            $item['username'] = $userInfo['username'];
            $item['media'] = json_encode($item['media']);
        }

        $result = $this->app->db->name('ShopGoodsComments')->insertAll($data['items']);
        if ($result) {
            $this->app->db->name('ShopOrder')->where('order_no', $data['order_no'])->update(['comment_status' => 1]);
            $this->success('评价成功', $data);
        } else {
            $this->error('评价失败', $data);
        }
    }


}